import json

from lxml import etree

import requests


def get_film_id(film_name):
    url = "https://maoyan.com/query?kw=" + film_name
    # print(url)
    response = requests.get(url)
    content = response.content.decode()
    # print(content)
    html = etree.HTML(content)
    try:

        name_list = html.xpath('//dl/dd//div[@class="channel-detail movie-item-title"]/@title')
        id_list = html.xpath('//dl/dd//div[@class="channel-detail movie-item-title"]/a/@data-val')
        # pub_date = html.xpath('//dl/dd//div[@class="movie-item-pub"]/text()')
        ret_list = []
        for name in name_list:
            item = {}
            film_id = bytes.decode(id_list[name_list.index(name)].encode('utf-8'))[9:-1]
            item["name"] = name
            item["id"] = film_id
            # item["pub_date"] = bytes.decode(pub_date[name_list.index(name)].encode('utf-8'))
            # print(item)
            ret_list.append(item)
        return ret_list
    except:
        pass

def get_hot_cmts(id):
    url = "http://m.maoyan.com/mmdb/comments/movie/%s.json" % id
    # print(url)
    response = requests.get(url)
    content = response.content.decode()
    # 热评json数据
    json_data = json.loads(content)['hcmts']
    return json_data
# get_hot_cmts(228866)